import shutil
from pathlib import Path
from datetime import datetime
import requests
from PIL import Image
from requests_toolbelt.multipart.encoder import MultipartEncoder

class EventUploader:
    def __init__(self):
        self.key_frames = [0, 3, 7]  # 对应第1,4,8张图片

    def generate_events(self, source_dir: str, output_dir: str):
        """生成事件包（GIF+关键帧）"""
        Path(output_dir).mkdir(parents=True, exist_ok=True)
        
        # 获取并排序源图片
        images = sorted(
            Path(source_dir).glob("*.jpg"),
            key=lambda x: int(x.stem.split('_')[-1])
        )

        for batch_idx in range(0, len(images), 8):
            batch = images[batch_idx:batch_idx+8]
            if len(batch) < 8:
                continue  # 跳过不足8张的批次

            # 创建事件目录
            event_id = f"event_{batch_idx//8:03d}"
            event_dir = Path(output_dir) / event_id
            event_dir.mkdir(exist_ok=True)

            # 保存关键帧
            key_files = []
            for idx in self.key_frames:
                src = batch[idx]
                dest = event_dir / f"key_{idx+1}.jpg"  # key_1.jpg, key_4.jpg, key_8.jpg
                shutil.copy(src, dest)
                key_files.append(dest)

            # 生成GIF
            gif_path = event_dir / f"{event_id}.gif"
            self._create_gif(batch, gif_path)

            # 记录时间戳
            (event_dir / "timestamp").write_text(datetime.now().isoformat())

    def _create_gif(self, images: list, output_path: Path):
        """生成GIF文件"""
        frames = []
        for img_path in images:
            with Image.open(img_path) as img:
                frames.append(img.resize((img.width//4, img.height//4)))
        
        frames[0].save(
            output_path,
            save_all=True,
            append_images=frames[1:],
            duration=200,
            loop=0,
            optimize=True
        )

    

# 使用示例
if __name__ == "__main__":
    uploader = EventUploader()

    events = "/data/control_communication/chunk_0000/chunk_0000_mp4/problem_cross"
    uploader.generate_events(
        source_dir=events,
        output_dir=events
    )
    
    
    print(f"成功上传: {report['success']}/{report['total']}")